package net.zjitc.servlet.dispacher;

import net.zjitc.servlet.annotation.ResustMapping;
import net.zjitc.utils.ClassUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by rj1502 on 2017/11/1.
 * 转发器，
 *
 */
@WebServlet(name = "DispacherServlet" ,urlPatterns = "/")
public class DispacherServlet extends HttpServlet {
   Map<String ,Method> urlMap = new HashMap<>();
   Map<Method,Object> methodMap = new HashMap<>();
    @Override
    public void init() throws ServletException {
        //先扫描所有的类对象（某个包下的）
        String scanPath = "net.zjitc.controller";
        List<Class> classes = ClassUtils.findAllClass(scanPath);
        for (Class c:classes){
            Object o = null;
            try {
                o  = c.newInstance();
                Method[] methods = c.getMethods();

                for (Method m : methods){
                    ResustMapping annotation = m.getAnnotation(ResustMapping.class);
                    if (annotation!= null){
                        String url = annotation.url();
                        urlMap.put(url,m);
                        methodMap.put(m,o);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //String uri = req.getRequestURI();
        //String url = req.getServletContext().getContextPath();
        String servletPath = req.getServletPath();
        Method m = urlMap.get(servletPath);
        Object o = methodMap.get(m);
        try {
            m.invoke(o,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
